import { ipcMain } from 'electron'
import * as cheerio from 'cheerio'
import ejs from 'ejs'
import fs from 'fs'
import pinyin from 'js-pinyin'
import prettier from 'prettier'

export const setupWebsiteToPageHandlers = () => {
  ipcMain.handle('website-to-page', (_event, richText: any) => {
    return new Promise(async (resolve) => {
      const cleanHtml = getCleanedRichText(richText)
      const tableConfig = getTableConfig(cleanHtml)
      const formConfig = getFormConfig(cleanHtml)
      const res = await renderPage(tableConfig, formConfig)
      resolve(res)
    })
  })
}

const renderPage = (tableConfig: any, formConfig: any) => {
  return new Promise((resolve, reject) => {
    fs.readFile('./src/main/handlers/websiteToPage/page.ejs', 'utf8', (err, template) => {
      if (err) {
        reject(err)
        console.error('Error reading template:', err)
        return
      }

      // 渲染模板，并传递变量
      const renderedTemplate = ejs.render(template, {
        tableConfig,
        formConfig
      })

      const formattedTemplate = prettier.format(renderedTemplate, {
        parser: 'vue',
        printWidth: 120,
        tabWidth: 4,
        useTabs: true
      })

      resolve(formattedTemplate)
    })
  })
}

const getCleanedRichText = (richText) => {
  const $ = cheerio.load(richText)
  // 先移除所有style属性中包含display:none的标签
  $('[style]').each(function () {
    const style = $(this).attr('style')
    if (style && /display\s*:\s*none/i.test(style)) {
      $(this).remove()
    }
  })
  // 递归移除所有空标签（无文本且无子元素）
  function removeEmptyTags() {
    let removed = false
    $('*').each(function () {
      if (!$(this).html()?.trim() && $(this).children().length === 0) {
        $(this).remove()
        removed = true
      }
    })
    if (removed) removeEmptyTags()
  }
  removeEmptyTags()
  // 移除所有svg标签及其内容
  $('svg').remove()
  const cleanHtml = $.html()
  return cleanHtml
}

const getFormConfig = (cleanHtml) => {
  const $ = cheerio.load(cleanHtml)
  const formConfig: any = {
    fields: []
  }
  // 遍历.el-form下所有label
  $('.el-form label').each(function () {
    const label = $(this).text().trim()
    if (label && label !== '请选择') {
      // 查找label最近的.el-form-item下.el-form-item__content的类型
      let type = 'any'
      const formItem = $(this).closest('.el-form-item')
      const content = formItem.find('.el-form-item__content')
      // 优先判断是否有多个.el-date-editor
      if (content.find('.el-date-editor').length > 1) {
        type = 'dateRange'
      } else if (content.find('.el-date-editor').length === 1) {
        type = 'date'
      } else {
        const firstChild = content.children().first()
        if (firstChild.hasClass('el-input')) {
          type = 'text'
        } else if (firstChild.hasClass('el-select')) {
          type = 'select'
        } else if (firstChild.hasClass('el-cascader')) {
          type = 'cascader'
        }
      }
      formConfig.fields.push({
        label: label.replace('*', ''),
        type,
        required: label.includes('*') ? true : false
      })
    }
  })
  formConfig.fields.forEach((item) => {
    item.name = getPinYin(item.label)
  })
  console.log(formConfig)
  return formConfig
}

const getTableConfig = (cleanHtml) => {
  const $ = cheerio.load(cleanHtml)
  const tableConfig: any = {
    columns: [],
    data: [],
    actionList: [],
    operateList: []
  }
  // 提取表头
  const header = $('.el-table__header thead')
  if (header.length > 0) {
    header
      .find('tr')
      .first()
      .find('th, td')
      .each(function () {
        const cell = $(this).find('.cell')
        const title = cell.text().trim()
        if (title && title !== '操作') {
          tableConfig.columns.push({
            title,
            dataIndex: getPinYin(title),
            width: 80 + title.length * 14
          })
        }
      })
  }
  // 提取表体数据
  const bodyRows = $('.el-table__body tr')
  if (bodyRows.length > 0 && tableConfig.columns.length > 0) {
    bodyRows.each(function () {
      const row: string[] = []
      $(this)
        .find('td')
        .each(function () {
          const cell = $(this).find('.cell')
          row.push(cell.text().trim())
        })
      const res = row.reduce((acc, cur, index) => {
        if (tableConfig.columns[index]?.dataIndex) {
          acc[tableConfig.columns[index].dataIndex] = cur
        }
        return acc
      }, {} as any)
      tableConfig.data.push(res)
    })
  }
  // 提取actionList：tbody td .cell下button元素的文案，去重
  const actionSet = new Set<string>()
  $('.el-table__body tr td .cell button').each(function () {
    const btnText = $(this).text().trim()
    if (btnText) {
      actionSet.add(btnText)
    }
  })
  tableConfig.actionList = Array.from(actionSet)
  // 提取operateList：.drop-box下第二个子元素的第一个子元素下所有button
  const operateSet = new Set<string>()
  $('.drop-box').each(function () {
    const firstChildOfLast = $(this).children().last().children().first()
    firstChildOfLast.find('button').each(function () {
      const btnText = $(this).text().trim()
      if (btnText) {
        operateSet.add(btnText)
      }
    })
  })
  tableConfig.operateList = Array.from(operateSet).filter(
    (item) => item !== '查询' && item !== '重置'
  )
  return tableConfig
}

const getPinYin = (text: string) => {
  text = text.replace(/[^a-zA-Z0-9\u4e00-\u9fa5]/g, '')
  const str = pinyin.getCamelChars(text).toLowerCase()
  return `_temp_${str}`
}
